<?php

namespace App\Utils;

class BaiDuVoice
{
    /**
     * 获取百度api token
     * @return false|mixed
     */
    public function getBaiduToken()
    {
        $curl = curl_init();
        $postData = array(
            'grant_type' => 'client_credentials',
            'client_id' => config('baiduvoice.api_key'),
            'client_secret' => config('baiduvoice.secret_key')
        );
        curl_setopt_array($curl, array(
            CURLOPT_URL => 'https://aip.baidubce.com/oauth/2.0/token',
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => false,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POSTFIELDS => http_build_query($postData)
        ));
        $response = curl_exec($curl);
        $response = json_decode($response);
        curl_close($curl);
        if (!isset($response->access_token) or !isset($response->scope)) {
            return false;
        }
        if (!in_array('audio_tts_post', explode(" ", $response->scope))) {
            // 请至网页上应用内开通语音合成权限
            return false;
        }

        $token = $response->access_token;

        return $token;
    }

    /**
     * 获取文字tts方法
     * @param string $text 文本
     * @return array code:200/500 message data['url']
     */
    public function tts(string $text): array
    {
        //短语音合成最好不超过40个字
        $text_len = mb_strlen($text);
        if ($text_len > 40) {
            return create_response_data('请输入少于40个字', false);
        }
        //获取百度api token
        $token = $this->getBaiduToken();
        if (!$token) {
            return create_response_data('获取语音token失败', false);
        }
        //拼接参数
        $params = array(
            'tex' => urlencode($text), // 为避免+等特殊字符没有编码，此处需要2次urlencode。
            'per' => config('baiduvoice.tts.per'),
            'spd' => config('baiduvoice.tts.spd'),
            'pit' => config('baiduvoice.tts.pit'),
            'vol' => config('baiduvoice.tts.vol'),
            'aue' => config('baiduvoice.tts.aue'),
            'cuid' => config('baiduvoice.cuid'),
            'tok' => $token,
            'lan' => 'zh', //固定参数
            'ctp' => 1, // 固定参数
        );
        $paramsStr = http_build_query($params);
        $url = 'http://tsn.baidu.com/text2audio';
        $url_mp3 = $url . '?' . $paramsStr;
        return create_response_data('成功', true, ['url' => $url_mp3]);
    }


}
